<template>
  <view class="container">
    <!-- Logo 区域 -->
    <view class="logo-container">
      <image src="/static/images/logo.png" mode="aspectFit" class="logo"></image>
      <text class="app-name">农检通</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <u-form :model="form" ref="uForm" labelPosition="left" labelWidth="160rpx">
        <!-- 手机号 -->
        <u-form-item label="手机号码">
          <u-input v-model="form.phone" placeholder="请输入手机号码" />
        </u-form-item>

        <!-- 密码 -->
        <u-form-item label="输入新密码">
          <u-input v-model="form.password" type="password" placeholder="请输入6~12位数字或字母" />
        </u-form-item>

        <!-- 确认密码 -->
        <u-form-item label="确认新密码">
          <u-input v-model="form.confirmPassword" type="password" placeholder="请再次确认密码" />
        </u-form-item>

        <!-- 验证码区域 -->
        <u-form-item label="验证码">
          <view class="code-input">
            <!-- 输入框 -->
            <u-input
              v-model="form.captcha"
              placeholder="请输入图形验证码"
              maxlength="4"
            />
            <!-- 验证码图片 -->
            <image
              :src="captchaUrl"
              @tap="refreshCaptcha"
              class="captcha-img"
              mode="aspectFit"
            />
          </view>
        </u-form-item>

        <!-- 注册按钮 -->
        <u-button
          type="success"
          @click="handleRegister"
          :loading="loading"
          style="width: 100%; margin-top: 60rpx;"
        >
          {{ loading ? '注册中...' : '注 册' }}
        </u-button>
      </u-form>
    </view>
  </view>
</template>

<script>
// 引入封装的请求方法（假设你使用的是类似 uView 的 $u.post 或自定义 post）
import {get ,post } from '@/utils/request';
import md5 from 'blueimp-md5';

export default {
  data() {
    return {
      loading: false,
      captchaUrl: '', // 图形验证码图片 Base64 数据
      uuid: '',       // 后端返回的验证码唯一标识
      form: {
        phone: '',
        password: '',
        confirmPassword: '',
        captcha: '' // 用户输入的图形验证码
      }
    };
  },
  mounted() {
    // 页面加载时获取图形验证码
    this.refreshCaptcha();
  },
  methods: {
    /**
     * 刷新图形验证码
     */
   async refreshCaptcha() {
       try {
         // ✅ 使用封装的 get，自动使用 BASE_URL
         const res = await get('/captchaImage');
   
         // ✅ 后端返回结构匹配：{ code: 200, uuid: '...', img: 'base64...' }
         if (res.code === 200) {
           this.uuid = res.uuid;
           this.captchaUrl = 'data:image/gif;base64,' + res.img;
         } else {
           uni.showToast({
             title: res.msg || '获取验证码失败',
             icon: 'none'
           });
         }
       } catch (err) {
         console.error('获取验证码错误:', err);
         uni.showToast({
           title: '网络异常，请重试',
           icon: 'none'
         });
         // 可选：延迟重试
         setTimeout(() => {
           this.refreshCaptcha();
         }, 1500);
       }
     },

    /**
     * 处理注册逻辑
     */
    async handleRegister() {
      const { phone, password, confirmPassword, captcha } = this.form;

      // 1. 基础校验
      if (!phone || !password || !confirmPassword || !captcha) {
        uni.showToast({ title: '请填写全部信息', icon: 'none' });
        return;
      }

      if (!/^1[3-9]\d{9}$/.test(phone)) {
        uni.showToast({ title: '手机号格式错误', icon: 'none' });
        return;
      }

      if (password !== confirmPassword) {
        uni.showToast({ title: '两次密码不一致', icon: 'none' });
        return;
      }

      if (password.length < 6 || password.length > 12) {
        uni.showToast({ title: '密码长度为6~12位', icon: 'none' });
        return;
      }

      // 2. 开始注册请求
      this.loading = true;
      try {
        const res = await post('/nongjt/userAuth/register', {
          mobilePhone: phone,
          password: md5(password),
          captcha: captcha, // 图形验证码
          uuid: this.uuid   // 验证码标识
        });

        if (res.code === 200) {
          uni.showToast({ title: '注册成功', icon: 'success' });
          setTimeout(() => {
            uni.navigateBack(); // 返回上一页
          }, 800);
        } else {
          uni.showToast({ title: res.msg || '注册失败', icon: 'none' });
          // 注册失败，刷新验证码
          this.refreshCaptcha();
        }
      } catch (err) {
        console.error('注册请求异常:', err);
        uni.showToast({
          title: err.msg || '请求失败，请检查网络',
          icon: 'none'
        });
        this.refreshCaptcha(); // 出错也刷新验证码
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 80rpx 0;
  gap: 10rpx;
}

.logo {
  width: 160rpx;
  height: 160rpx;
}

.app-name {
  font-size: 40rpx;
  font-weight: bold;
  color: #3cc51f;
}

.form-container {
  width: 100%;
  max-width: 600rpx;
  padding: 0 30rpx;
}

.code-input {
  display: flex;
  align-items: center;
}

.code-input .u-input {
  flex: 1;
  margin-right: 20rpx;
}

.captcha-img {
  width: 160rpx;
  height: 80rpx;
  border-radius: 8rpx;
  border: 1px solid #ddd;
}
</style>